package com.bupt.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bupt.config.ExceptionInfo;
import com.bupt.exceptions.BusinessException;
import com.sun.jdi.InternalException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 用于解决feign调用不传递异常信息问题
 */
//@Configuration
@Slf4j
public class FeignErrorDecoder implements ErrorDecoder {
    @Override
    public Exception decode(String s, Response response) {
        try {
            if (response.body() != null) {
                String body = Util.toString(response.body().asReader(StandardCharsets.UTF_8));
                log.error(body);
                ExceptionInfo exceptionInfo = JSON.parseObject(body, new TypeReference<ExceptionInfo>() {
                });
//                //利用反射创建自定义异常类
//                Class<?> aClass = Class.forName(exceptionInfo.getException());
//
//                //获取异常信息（是ResultCode的json字符串）
//                String jsonMsg = exceptionInfo.getMessage();
//                Map map = JSON.parseObject(jsonMsg, Map.class);
//                Integer code = (Integer) map.get("code");
//                String message = (String) map.get("message");
//                //把类的实例返回
//                return (Exception) aClass.getDeclaredConstructor(Integer.class, String.class).newInstance(code, message);
//                return (Exception) aClass.getDeclaredConstructor(ResultCode.class).newInstance(resultCode);
                //获取异常信息（是ResultCode的json字符串）
                String jsonMsg = exceptionInfo.getMessage();
                Map map = JSON.parseObject(jsonMsg, Map.class);
                Integer code = (Integer) map.get("code");
                String message = (String) map.get("message");
                //把类的实例返回
                return new BusinessException(code, message);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new InternalException(e.getMessage());
        }

        return new InternalException("系统异常,请联系管理员");
    }

}
